import React, { useEffect, useState } from 'react'
import { Input, Button } from 'antd';
import styles from './index.module.css'


const reqUrl = "ws://172.26.2.18:8081/WCS/WebSocket/test01";
let websocket = null;
let intervalId = null;

function Test01() {
    //长链接地址


    const [text, setText] = useState('')

    //[]空数组相当于componentDidMount
    useEffect(() => {
        initData()
        return () => {
            if (intervalId != null) {
                clearInterval(intervalId);
            }
        }
    }, []);

    function initData() {
        if ("WebSocket" in window) {
            websocket = new WebSocket(reqUrl);
        } else {
            alert("当前浏览器不支持长链接,请更换浏览器")
        }
        //连接成功建立触发的方法
        websocket.onopen = function (event) {
            console.log('websocket连接成功', event);
        }
        //接收到消息触发的方法
        websocket.onmessage = function (event) {
            //将服务端发来的消息拼接到div中
            console.log('onmessage', event.data);
        }
        //连接关闭触发的方法
        websocket.onclose = function () {
            console.log('WebSocket 连接已关闭');
        }
        //连接发生错误触发的方法
        websocket.onerror = function (error) {
            websocket.close();
            console.log('WebSocket 错误', error);
        }
        //监听窗口关闭事件,当窗口关闭后要主动关闭websocket连接
        websocket.opbeforeunload = function () {
            websocket.close();
            console.log('opbeforeunload');
        }
        //心跳链接
        intervalId = setInterval(function () {
            websocket.send('心跳')
        }, 1000 * 30);

    }


    function onChangeTest(val) {
        let value = val.target.value
        setText(value);
    }

    function clickSend() {
        websocket.send(text)
    }

    return (
        <div>
            <div >
                <Input className={styles.inputContent} maxLength={20} placeholder={'请输入内容...'} onChange={onChangeTest} />
                <Button onClick={() => { clickSend() }} className={styles.btnSend} type="primary">发送</Button>
            </div>
        </div>
    )
}

export default Test01;
